import { useCallback, useRef, useState } from 'react'

// add loading effect to submit button
export function useSubmit(delaySec = 1.5) {
  const [loading, setLoading] = useState(false)

  const handlerRef = useRef<Fn>()

  const callback = useCallback(
    async function (...args: any[]) {
      setLoading(true)
      // at least loading for a while
      await Promise.allSettled([
        await handlerRef.current!(...args),
        new Promise((resolve) => setTimeout(resolve, delaySec * 1000, true)),
      ])
      setLoading(false)
    },
    [delaySec],
  )

  const submitCallback = useCallback(
    function (handler: Fn) {
      // ensure handler is fresh
      handlerRef.current = handler

      return callback
    },
    [callback],
  )

  return { loading, submitCallback }
}
